﻿//
layui.use(['jquery', 'table', 'ajaxUtil', 'permissionUtil', 'switchTab', 'msgTemplate', 'utilDateKit'], function () {
    var table = layui.table,
        $ = layui.jquery,
        ajaxutil = layui.ajaxUtil,
        permissionUtil = layui.permissionUtil,
        switchTab = layui.switchTab,
        msgTemplate = layui.msgTemplate,
        utilDateKit = layui.utilDateKit;

    //聊天缓存数据
    var ChatMsgCacheList = [];

    var ChatMsgParam = {
        monitorConnectionId: ''  //当前聊天窗口链接Id
    }
    var UserInfo = {
        connectionId: '',
        nickName: '',
        headUrl: ''
    };

    var connection = new signalR.HubConnectionBuilder()
        .withUrl("/humMain")
        //设置重连时间0s，1s,5s,30s,断开连接
        .withAutomaticReconnect([0, 1000, 2000, 3000, 4000, 5000, 10000, 20000, 30000, null])
        .configureLogging(signalR.LogLevel.Information)
        .build();

    var DocumentTitle = ['MKAdmin管理系统'];

    var loadClientAll = function (clientList) {
        if (clientList != null && clientList.length > 0) {
            $.each(clientList, function (index, item) {
                loadMenu(item);
            });

            initMenuEvent();
        }
        else {
            alert('当前没有用户');
        }
    }

    var loadMenu = function (clientInfo) {
        var menuHtml = '<li class="" id="' + clientInfo.connectionId + '" title="' + clientInfo.nickName + '">' +
            '<a class="zf-groud-name clearfix" >' +
            '   <i class="groupTime">' + utilDateKit.getMenuMsgTime(clientInfo.sendTime) + '</i>' +
            '   <i class="groupDisturb"></i>' +
            '   <img title="在线" class="onLine" src="/Images/onLine.png" alt="">' +
            '       <img class="pull-left" src="' + clientInfo.headUrl + '" alt="">' +
            '       <h5 class="pull-left">' +
            '           <p>' +
            '               <span class="GroupChat_GroupName">' + clientInfo.nickName + '</span>' +
            '           </p>' +
            '           <span class="GroupChat_NewMsgDesc"></span>' +
            '       </h5>' +
            '</a>' +
            '</li>';
        if ($('.zf-group-chat-list li').length > 0) {
            $('.zf-group-chat-list').prepend(menuHtml)
        }
        else {
            $('.zf-group-chat-list').append(menuHtml);
        }
    }

    var loadMsg = function (content) {
        //console.log(msg);
        //菜单
        loadMenuMsg(content);

        //消息正文
        loadContentMsg(content);
    }
    //加载菜单消息
    var loadMenuMsg = function (content) {
        var elemtConnection = ("#" + content.senderConnectionId);

        if ($(elemtConnection).length <= 0) {
            var clientInfo = {
                ConnectionId: content.senderConnectionId,
                NickName: content.senderNickName,
                HeadUrl: content.senderHeadUrl,
                SendTime: content.sendTime
            };
            loadMenu(clientInfo);
            initMenuEvent();
        }

        //刷新菜单群未读消息信息
        $(elemtConnection + ' .GroupChat_NewMsgDesc').text(content.text);
        //刷新聊天时间
        $(elemtConnection + ' .groupTime').text(utilDateKit.getMenuMsgTime(content.sendTime));

        //正在监控的聊天窗口不更新
        if (ChatMsgParam.monitorConnectionId != content.senderConnectionId) {
            //更新未读消息数
            setMsgUnReadNumberLabel(content);

            //置顶
            $(".groupChatElement ul li:eq(0)").before($(elemtConnection));
        }
    }
    //加载正文消息
    var loadContentMsg = function (content) {
        if (ChatMsgParam.monitorConnectionId == content.senderConnectionId) {
            msgTemplate.loadMsg(content);
        }
        setChatPanelScroll();
    }
    //加载缓存消息
    var loadCacheMsgContent = function (connectionId) {
        var msgList = ChatMsgCacheList.filter(function (item, index) {
            return item.connectionId == connectionId;
        });
        if (msgList != null && msgList.length > 0) {

            if (msgList[0].content != null && msgList[0].content.length > 0) {
                $.each(msgList[0].content, function (index, item) {
                    loadContentMsg(item);
                });
            }
        }
    }

    var setMsgUnReadNumberLabel = function (content) {
        //获取页面上未读消息个数
        var pageUnReadNumber = 0;
        var elemtConnection = ("#" + content.senderConnectionId + ' .chartNumber');
        if ($(elemtConnection).length > 0) {
            pageUnReadNumber = parseInt($(elemtConnection).text());
            $(elemtConnection).text(pageUnReadNumber + 1);
        }
        else {
            var unReadNumber = ' <b class="chartNumber">1</b>';
            //添加标签
            $('#' + content.senderConnectionId).prepend(unReadNumber);
        }
    }

    var clientOnDisconnected = function (connectionId) {
        var onLineStatusElemt = getOnLineStatusLabel(0);
        $("#" + connectionId + ' .onLine').remove();

        $("#" + connectionId + ' .zf-groud-name').prepend(onLineStatusElemt);

        var elemtConnection = ("#" + connectionId);
        if ($(elemtConnection).length > 0) {
            //刷新菜单群未读消息信息
            $(elemtConnection + ' .GroupChat_NewMsgDesc').text('用户已下线');
        }
    }

    var connectionSignalr = function () {
        try {
            if (!connection.connectionStarted) {
                //每次调用会生成新的connectionId
                connection.start().then(function (message) {

                });
                //    .catch(function (error) {
                //    console.info('connection.start.catch', error);
                //});
            }
        } catch (e) {
            console.info('连接失败', err);
            setTimeout(() => connectionSignalr(), 5000);
        }
    }

    var initSignalr = function () {
        //debugger;
        //connection.start().then(function (message) {
        //    //debugger;
        //    //document.getElementById("sendButton").disabled = false;
        //    console.log('connection.start().then');
        //}).catch(function (err) {
        //    //debugger;
        //    console.log('connection.start.catch');
        //    console.log(err.toString);
        //    //return console.error(err.toString());
        //});
        connectionSignalr();
        connection.onclose(async () => {
            console.info('监听到连接关闭');
            connectionSignalr();
        });
        //connection.disconnected(function () {
        //    console.info('监听到关闭 disconnected');
        //});
        connection.onreconnecting(function (info) {
            console.info('-------signalr-- onreconnecting-正在连接', info);
        });
        connection.onreconnected((connectionId) => {
            //todo
            console.info('-----------signalr-- onreconnected-连接成功' + connectionId);
        });
        //connection.disabled(function (info) {
        //    console.info('----------------------------------signalr-- disabled', info);
        //});
        //setInterval(function () {
        //    console.log('check connectionSignalr')
        //    connectionSignalr();
        //}, 3000);

        //用户离线通知
        connection.on("noticeClientOnDisconnected", function (connectionId) {
            clientOnDisconnected(connectionId);
        });
        connection.on("noticeClientOnLine", function (userInfo) {
            console.info('--------noticeClientOnLine', userInfo);
            $(".nobody-main").hide();
            $(".chat-main").show();
            loadMenu(userInfo);
            initMenuEvent()
        });
        connection.on("loadClientAll", function (user, myInfo) {
            //debugger;
            if (user == null || user.length <= 0) {
                //NickName
                //没有用户在线
                $(".chat-head-url").attr("src", myInfo.headUrl);
                $(".nobody-main").show();
                $(".chat-main").hide();
                initJoinUser();
            }
            else {
                $(".nobody-main").hide();
                $(".chat-main").show();
                loadClientAll(user);
            }
            //debugger;
            UserInfo.connectionId = myInfo.connectionId;
            UserInfo.nickName = myInfo.nickName;
            UserInfo.headUrl = myInfo.headUrl;
        });
        //接收消息
        connection.on("acceptMsgFromClient", function (msgContent) {
            msgContent.typeCode = 0;
            loadMsg(msgContent);
            saveMsg(msgContent);

            DocumentTitle = ['新消息', '...'];
            playVoice();
        });
    }

    var initJoinUser = function () {
        $(".join-new-user").unbind('click');
        $(".join-new-user").click(function () {
            //打开新页面
            //window.open('/?id=150010');
            window.open('/');
        });
    }

    var initMenuEvent = function () {
        $(".zf-group-chat-list li").unbind('click');
        $(".zf-group-chat-list li").click(function () {
            //切换选中样式
            $(".zf-group-chat-list li").removeClass('activeLi');
            $(this).addClass('activeLi');
            $(this).find('.chartNumber').remove();
            $(".GroupChatIndex_InfoShow").empty();

            //切换监听消息参数
            ChatMsgParam.monitorConnectionId = $(this).attr("Id");

            var nickName = $(this).find(".GroupChat_GroupName").text();
            $("#GroupChatIndex_GroupName").text(nickName);

            //加载聊天内容
            loadCacheMsgContent(ChatMsgParam.monitorConnectionId);

            DocumentTitle = ['MKAdmin管理系统'];
        });

        var menuConnectionId = "";
        //菜单右键
        $('.zf-group-chat-list li').unbind("contextmenu");
        $('.zf-group-chat-list li').bind("contextmenu", function (e) {
            //记录选中菜单
            menuConnectionId = $(this).attr("Id");

            var contextMenuHeiht = $(window).height();
            $(window).resize(function () {
                contextMenuHeiht = $(window).height();
            });
            var _this = $(this)
            $('.zf-group-chat-list li').removeClass('activeGroundRight');

            var activeGroundList = $(this).hasClass('activeLi');
            if (activeGroundList) {
                $(this).css({ 'background': '#c4c4c5' })
            } else {
                $(this).addClass('activeGroundRight')
            }

            var scrollX = e.pageX;
            var scrollY = e.pageY;

            var contextMenuHeight = $("#contextMenu").height();
            if (scrollY + contextMenuHeight >= contextMenuHeiht) {
                var popTopY = scrollY - contextMenuHeight;
                $("#contextMenu").css({ "top": popTopY + 'px', "left": scrollX, 'z-index': '500', "display": "block" })
            } else {
                $("#contextMenu").css({ "top": scrollY, "left": scrollX, 'z-index': '500', "display": "block" })
            }

            return false;
        });

        $(document).unbind('click');
        $(document).click(function () {
            $('#contextMenu').hide();
            $(".zf-group-chat-list li").removeClass('activeGroundRight');
        });

        $("#contextMenu p").unbind('click');
        $("#contextMenu p").click(function () {
            //删除
            if ($(this).hasClass('delete')) {
                $('.zf-group-chat-list' + ' #' + menuConnectionId).remove();

                if (ChatMsgParam.monitorConnectionId == menuConnectionId) {
                    ChatMsgParam.monitorConnectionId = "";
                    $("#GroupChatIndex_GroupName").text('');
                    $("#GroupChatIndex_GroupName").text('');
                    $(".GroupChatIndex_InfoShow").empty();
                }
            }
            $('#contextMenu').hide();
        });
    }

    var setChatPanelScroll = function () {
        $(".pcDetailAllGroup").scrollTop(10000000);
    }

    var initEvent = function () {
        //发送消息
        $(".activeSend").unbind('click');
        $(".activeSend").click(function () {
            if (ChatMsgParam.monitorConnectionId == "") {
                alert('请选中一个用户进行发送消息');
                return;
            }

            var content = {
                receiverConnectionId: ChatMsgParam.monitorConnectionId,
                msgType: 0,
                text: '',
                imgUrl: ''
            }

            content.text = $("#noticeAdvertis").val();
            if (content.text == '') {
                alert('发送内容不能为空');
                return;
            }

            connection.invoke('sendMessage', content).catch(err => {
                console.log('connection.invoke.sendMessage.catch');
                alert(err.toString())
            });

            $("#noticeAdvertis").val('');
            var msgContent =
            {
                senderConnectionId: ChatMsgParam.monitorConnectionId,
                typeCode: 1,
                senderNickName: UserInfo.nickName,
                senderHeadUrl: UserInfo.headUrl,
                msgType: 0,
                text: content.text,
                imgUrl: '',
                sendTime: new Date()
            };
            loadMsg(msgContent);
            saveMsg(msgContent);

            DocumentTitle = ['MKAdmin管理系统'];
        });

        $("#noticeAdvertis").keydown(function (e) {
            var theEvent = e || window.event;
            var code = theEvent.keyCode || theEvent.which || theEvent.charCode;

            //enter键
            if (theEvent.ctrlKey && code == 13) {
                $("#noticeAdvertis").val($("#noticeAdvertis").val() + '\n');
            }
            else if (code == 13) {
                //alert(2);
                $(".activeSend").click();

                // 禁止换行
                e.cancelBubble = true;
                e.preventDefault();
                e.stopPropagation();
            }
        });
    }

    var saveMsg = function (content) {
        try {
            var msgList = ChatMsgCacheList.filter(function (item, index) {
                return item.connectionId == content.senderConnectionId;
            });
            if (msgList != null && msgList.length > 0) {
                //添加内容
                msgList[0].content.push(content);
            }
            else {
                var _msgList = {};
                _msgList.content = [];
                _msgList.connectionId = content.senderConnectionId;
                _msgList.content.push(content);

                ChatMsgCacheList.push(_msgList);
            }

        } catch (e) {

        }
    }

    //在线状态
    var getOnLineStatusLabel = function (onlineStatus) {
        var statusLabel = '';
        if (onlineStatus == 1) {
            statusLabel = '    <img title="在线" class="onLine" src="/images/onLine.png" alt="">';
        }
        else {
            statusLabel = '    <img title="离线" class="onLine" src="/images/overLine.png" alt="">';
        }
        return statusLabel;
    }

    var init = function () {
        initSignalr();
        initEvent();

        setPageTitle();
    }

    var playVoice = function () {
        var audioEle = document.getElementById("NewMessageRemind");
        audioEle.play();   //播放
    }

    var setDocumentTitle = function (title) {
        $(top.document).attr("title", title);
    }

    function guid() {
        return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
            var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
            return v.toString(16);
        });
    }

    var setPageTitle = function () {
        var index = 0;

        window.setInterval(function () {
            var len = DocumentTitle.length;
            setDocumentTitle(DocumentTitle[index]);
            index++;
            if (index >= len) {
                index = 0;
            }
        }, 1000);
    }

    init();
});